import jpype
import json

class DBOpr_j:
    def __init__(self, dbInfo):
        self.path = f"-Djava.class.path={__file__.rstrip('dbopr.py')}/dbopr_1.0.jar"
        self.dbInfo = {
            "url": f"jdbc:{dbInfo['dbtype']}://{dbInfo['ip']}:{dbInfo['port']}/{dbInfo['dbName']}?useSSL=false",
            "driver": f"com.{dbInfo['dbtype']}.jdbc.Driver",
            "user": dbInfo['user'],
            "pass": dbInfo['passwd']
        }
    def select(self, sql, keepup=True):
        jvmPath = jpype.getDefaultJVMPath()
        try: jpype.startJVM(jvmPath, "-ea", self.path)
        except: pass
        JDClass = jpype.JClass("Main")
        jd = JDClass()
        result_str = jd.select(self.dbInfo, sql)
        result = json.loads(str(result_str))
        if not keepup: jpype.shutdownJVM()
        return result
    def execs(self, sqls, rollback=False, keepup=True):
        jvmPath = jpype.getDefaultJVMPath()
        try: jpype.startJVM(jvmPath, "-ea", self.path)
        except: pass
        JDClass = jpype.JClass("Main")
        jd = JDClass()
        result_str = jd.execsqls(self.dbInfo, sqls, rollback)
        result = json.loads(str(result_str))
        if not keepup: jpype.shutdownJVM()
        return result
    def exec(self, sql, rollback=False, keepup=True):
        jvmPath = jpype.getDefaultJVMPath()
        try: jpype.startJVM(jvmPath, "-ea", self.path)
        except: pass
        JDClass = jpype.JClass("Main")
        jd = JDClass()
        result_str = jd.execsqls(self.dbInfo, [sql], rollback)
        result = json.loads(str(result_str))
        if not keepup: jpype.shutdownJVM()
        return result

